package edu.zjucst.spb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.zjucst.spb.dao.mapper.ActivityMapper;
import edu.zjucst.spb.domain.entity.*;
import edu.zjucst.spb.domain.entity.message.SystemMessage;
import edu.zjucst.spb.domain.vo.UserVo;
import edu.zjucst.spb.service.*;
import edu.zjucst.spb.util.BranchUtil;
import edu.zjucst.spb.util.SessionUtil;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static edu.zjucst.spb.constant.ActivityConstant.ACTIVITY_TYPE_REPORT;
import static edu.zjucst.spb.constant.ActivityConstant.ACTIVITY_TYPE_TRAINING;
import static edu.zjucst.spb.constant.StageConstant.*;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity>  implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private BranchService branchService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private SpbUserService spbUserService;

    @Override
    @Transactional
    public int insert(List<Activity> activityList) {
        int count = 0;
        for (Activity activity:activityList) {
            count += activityMapper.insert(activity);
        }
        return count;
    }

    @Override
    public IPage<Activity> selectActivityList(Page<Activity> page,String developmentPhase, Integer days , String activityNumber) {
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        if(days!=null){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            if(days==7){
                calendar.add(Calendar.DATE, - 7);//减几就是几天之前
            }else if(days==30) {
                calendar.add(Calendar.MONTH, -1);
            }else if(days==180){
                calendar.add(Calendar.MONTH, -6);
            }
            Date d = calendar.getTime();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String transformDate=simpleDateFormat.format(d);
            wrapper.ge("activity_date",d);
        }
        if(developmentPhase!=null){
            wrapper.eq("development_phase",developmentPhase);
        }
        if(activityNumber!=null){
            wrapper.eq("activity_number",activityNumber);
        }
        IPage<Activity> activityPage = activityMapper.selectPage(page, wrapper);
        Role role = roleService.findRoleById(SessionUtil.getRoleId());
        Branch branch = branchService.findBranchById(SessionUtil.getBranchId());
        if(role.getRoleName().equals("支部书记")){
            List<Activity> activities = new ArrayList<>();
            for (Activity activity:activityPage.getRecords()
            ) {
                SpbUser user = spbUserService.findUserByNumber(activity.getUserNumber());
                if(BranchUtil.checkBranch(user,branch.getBranchName())){
                    activities.add(activity);
                }
            }
            activityPage.setRecords(activities);
        }
        return activityPage;
    }

    @Override
    @Transactional
    public int update(String activityNumber, List<UserVo> userList, String state) {
        int cnt = 0;
//        Role role = roleService.findRoleById(SessionUtil.getRoleId());
//        Branch branch = branchService.findBranchById(SessionUtil.getBranchId());
//        for (UserVo user:userList) {
//            SpbUser user1 = spbUserService.findUserByNumber(user.getUserNumber());
//            if(role.getRoleName().equals("支部书记") && !BranchUtil.checkBranch(user1,branch.getBranchName())){
//                throw new AuthorizationException();
//            }
//            QueryWrapper<Activity> wrapper = new QueryWrapper<>();
//            wrapper.eq("activity_number",activityNumber);
//            wrapper.eq("user_number",user.getUserNumber());
//            Activity activity = activityMapper.selectOne(wrapper);
//            activity.setState(state);
//            //自动接入思想汇报和党校培训时间
//            Stage stage = stageService.selectStageByNumber(activity.getUserNumber());
//            SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
//            String date = f.format(activity.getActivityDate());
//            if(activity.getActivityType().equals(ACTIVITY_TYPE_TRAINING)){
//                switch (activity.getDevelopmentPhase()){
//                    case ACTIVIST:stage.setActivistPartyTraining( stage.getActivistPartyTraining()+ date + ";" );
//                    case DEVELOP:stage.setDevelopPartyTraining( stage.getDevelopPartyTraining() + date + ";" );
//                    case PREPARE:stage.setPreparePartyTraining(stage.getPreparePartyTraining() + date + ";");
//                }
//            }else if(activity.getActivityType().equals(ACTIVITY_TYPE_REPORT)){
//                switch (activity.getDevelopmentPhase()){
//                    case ACTIVIST:stage.setThoughtReport(stage.getThoughtReport() + date + ";");
//                    case PREPARE:stage.setPrepareThoughtReport(stage.getPrepareThoughtReport() + date + ";");
//                }
//            }
//            stageService.updateStage(stage);
//            //疑问
//            cnt+=activityMapper.updateById(activity);
//        }
        return cnt;
    }

    @Override
    public int delete(String activityNumber) {
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.eq("activity_number",activityNumber);
        return activityMapper.delete(wrapper);
    }


    @Override
    public String selectActivityNumber() {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String date = f.format(new Date(System.currentTimeMillis()));
//        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
//        Activity activity = activityMapper.selectOne(
//            wrapper.likeRight("activity_number",date)
//                .select("activity_number")
//                .orderByDesc("activity_number")
//                .last("limit 1")
//        );

        LambdaQueryWrapper<Activity> wrapper = new LambdaQueryWrapper<>();
        Activity activity = activityMapper.selectOne(
            wrapper.likeRight(Activity::getActivityNumber,date)
                .select(Activity::getActivityNumber)
                .orderByDesc(Activity::getActivityNumber)
                .last("limit 1")
        );

        if(activity==null){
            return date+"000";
        }else{
            Long tmp = Long.parseLong(activity.getActivityNumber())+1;
            return Long.toString(tmp);
        }

    }


}
